from django.contrib import admin
from .models import Ticket, MaintenanceRecord

class MaintenanceRecordInline(admin.TabularInline):
    model = MaintenanceRecord
    extra = 0
    readonly_fields = ('created_at',)
    fields = ('technician', 'description', 'parts_used', 'hours_spent', 'created_at')

@admin.register(Ticket)
class TicketAdmin(admin.ModelAdmin):
    list_display = ('title', 'status', 'priority', 'created_by', 'assigned_to', 'created_at')
    list_filter = ('status', 'priority', 'created_at')
    search_fields = ('title', 'description', 'created_by__username', 'assigned_to__username')
    readonly_fields = ('created_at', 'updated_at', 'completed_at')
    fieldsets = (
        ('基本信息', {
            'fields': ('title', 'description', 'status', 'priority')
        }),
        ('人员分配', {
            'fields': ('created_by', 'assigned_to')
        }),
        ('设备信息', {
            'fields': ('assets',)
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at', 'completed_at')
        }),
    )
    inlines = [MaintenanceRecordInline]
    
    def save_model(self, request, obj, form, change):
        # 如果工单状态变为已完成，自动设置完成时间
        if obj.status == 'completed' and not obj.completed_at:
            from django.utils import timezone
            obj.completed_at = timezone.now()
        super().save_model(request, obj, form, change)

@admin.register(MaintenanceRecord)
class MaintenanceRecordAdmin(admin.ModelAdmin):
    list_display = ('ticket', 'technician', 'hours_spent', 'created_at')
    list_filter = ('created_at', 'technician')
    search_fields = ('ticket__title', 'description', 'technician__username')
    readonly_fields = ('created_at',)
    date_hierarchy = 'created_at'
